import React, { useEffect, useState, useMemo } from 'react';
import { Table, Button, Space, message, Popconfirm } from 'antd';
import { Article } from '@/types/article';
import { articleApi } from '@/api';
import { useNavigate } from 'react-router-dom';
import { PageHeader } from '@/components/PageHeader';
import { useTranslation } from 'react-i18next';

export const ArticleList: React.FC = () => {
    const { t } = useTranslation();
    const [articles, setArticles] = useState<Article[]>([]);
    const [loading, setLoading] = useState(false);
    const navigate = useNavigate();

    const fetchArticles = async () => {
        setLoading(true);
        try {
            const { data } = await articleApi.list();
            setArticles(data);
        } catch (error) {
            message.error(t('article.action.fetchListError'));
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchArticles();
    }, []);  // 添加空依赖数组

    const handleDelete = async (id: string) => {
        try {
            await articleApi.delete(id);
            message.success(t('article.delete.success'));
            await fetchArticles();  // 等待获取最新数据
        } catch (error) {
            message.error(t('article.delete.error'));
        }
    };

    const columns = useMemo(() => [
        {
            title: t('article.form.title'),
            dataIndex: 'title',
            key: 'title',
        },
        {
            title: t('article.form.category'),
            dataIndex: 'category',
            key: 'category',
        },
        {
            title: t('article.form.status'),
            dataIndex: 'published',
            key: 'published',
            render: (published: boolean) => (
                <span>{published ? t('article.status.published') : t('article.status.draft')}</span>
            ),
        },
        {
            title: t('article.list.updateTime'),
            dataIndex: 'updatedAt',
            key: 'updatedAt',
            render: (date: string) => new Date(date).toLocaleString(),
        },
        {
            title: t('article.list.operations'),
            key: 'action',
            render: (_: any, record: Article) => (
                <Space>
                    <Button onClick={() => navigate(`/edit/${record.id}`)}>
                        {t('common.edit')}
                    </Button>
                    <Popconfirm
                        title={t('article.delete.title')}
                        okText={t('common.confirm')}
                        cancelText={t('common.cancel')}
                        onConfirm={() => handleDelete(record.id)}
                    >
                        <Button danger>{t('common.delete')}</Button>
                    </Popconfirm>
                </Space>
            ),
        },
    ], [t, navigate]);  // 添加依赖项

    return (
        <div>
            <PageHeader
                title={t('article.title')}
                extra={
                    <Button type="primary" onClick={() => navigate('/create')}>
                        {t('article.create')}
                    </Button>
                }
            />
            <Table
                columns={columns}
                dataSource={articles}
                rowKey="id"
                loading={loading}
                pagination={{
                    showSizeChanger: true,
                    showTotal: (total) => t('article.list.total', { total }),
                }}
            />
        </div>
    );
};

export default ArticleList;